import React, { useImperativeHandle, useState } from 'react'
import { Form, Input, Modal, message } from 'antd'
import { IModalProps, ModelAction } from '@/types/modal'
import { createRole, editRole } from '@/api/roles'
import { IRoleItem } from '@/types/roles'

const CreateRole: React.FC<IModalProps<IRoleItem>> = props => {
  const [action, setAction] = useState<ModelAction>('create')
  const [visiable, setVisiable] = useState(false)
  const [form] = Form.useForm()

  // 自定义mRef,将open方法暴露给父组件使用
  useImperativeHandle(props.mRef, () => {
    return {
      open
    }
  })
  // 显示
  const open = (type: ModelAction, data?: IRoleItem) => {
    console.log('open:', type, data)
    if (data) {
      form.setFieldsValue(data)
    }
    setAction(type)
    setVisiable(true)
  }

  // 提交
  const handleSubmit = () => {
    form.validateFields().then(vaild => {
      if (vaild) {
        const params = {
          ...form.getFieldsValue()
        }
        console.log(params)
        if (action === 'create') {
          createRole(params).then(() => {
            message.success('创建成功')
            props.update()
          })
        } else {
          editRole(params).then(() => {
            message.success('修改成功')
            props.update()
          })
        }
        onCancel()
      }
    })
  }

  // 关闭
  const onCancel = () => {
    setVisiable(false)
    form.resetFields()
  }

  return (
    <Modal
      title={action === 'edit' ? '编辑角色' : '创建角色'}
      width={800}
      okText='确定'
      cancelText='取消'
      open={visiable}
      onCancel={onCancel}
      onOk={handleSubmit}
    >
      <Form form={form} labelAlign='right' labelCol={{ span: 4 }}>
        <Form.Item hidden name='_id'>
          <Input />
        </Form.Item>
        <Form.Item label='角色名称' name='roleName' rules={[{ required: true, message: '请输入角色名称' }]}>
          <Input></Input>
        </Form.Item>
        <Form.Item label='备注' name='remark'>
          <Input></Input>
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default CreateRole
